package com.wfh.aigenerator.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.wfh.aigenerator.common.ErrorCode;
import com.wfh.aigenerator.exception.BusinessException;
import com.wfh.aigenerator.exception.ThrowUtils;
import com.wfh.aigenerator.manager.ObsManager;
import com.wfh.aigenerator.service.ScreenshotService;
import com.wfh.aigenerator.utils.WebScreenHotUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * @Title: ScreenshotServiceImpl
 * @Author wangfenghuan
 * @Package com.wfh.aigenerator.service
 * @Date 2025/8/8 21:33
 * @description:
 */
@Service
@Slf4j
public class ScreenshotServiceImpl implements ScreenshotService {

    @Resource
    private ObsManager obsManager;

    /**
     * 产生并上传截图
     * @param url
     * @return
     */
    @Override
    public String genAndUploadScreenshot(String url) {
        ThrowUtils.throwIf(StrUtil.isBlank(url), ErrorCode.PARAMS_ERROR, "url不能为空");
        log.info("开始生成并上传截图，url:{}", url);
        // 生成本地截图
        String s = WebScreenHotUtils.takeScreenshot(url);
        ThrowUtils.throwIf(StrUtil.isBlank(s), ErrorCode.PARAMS_ERROR, "截图生成失败");
        try {
            // 上传到对象存储
            String upload = uploadToObs(s);
            if (StrUtil.isBlank(upload)) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR);
            }
            log.info("截图上传成功，url:{}", upload);
            return upload;
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "截图上传失败");
        } finally {
            // 清理本地文件
            cleanFile(s);
        }
    }

    /**
     * 上传文件到对象存储
     * @param localFilePath
     * @return
     */
    private String uploadToObs(String localFilePath){
        if (StrUtil.isBlank(localFilePath)) {
            return null;
        }
        File file = new File(localFilePath);
        if (!file.exists()) {
            log.error("本地文件不存在，路径:{}", localFilePath);
            return null;
        }
        String fileName =  UUID.randomUUID().toString().substring(0, 8) + "_compressed.jpg";
        String s = genKey(fileName);
        try {
            return obsManager.upload(file, s);
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "截图上传失败");
        }
    }

    /**
     * 生成截图对象的存储键
     * @param fileName
     * @return
     */
    private String genKey(String fileName) {
        String path = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
        return String.format("screenshots/%s/%s", path, fileName);
    }

    /**
     * 清理本地文件
     * @param localPath
     */
    private void cleanFile(String localPath) {
        File file = new File(localPath);
        if (file.exists()) {
            String absolutePath = file.getAbsolutePath();
            FileUtil.del(absolutePath);
            log.info("清理本地文件成功，路径:{}", absolutePath);
        }
    }
}
